#!/usr/bin/env python

import optparse
import os
import json
import subprocess
import sys

root_dir = os.path.dirname(__file__)

# parse our options
parser = optparse.OptionParser()

(options, args) = parser.parse_args()


def b(value):
  """Returns the string 'true' if value is truthy, 'false' otherwise."""
  if value:
    return 'true'
  else:
    return 'false'

def uname(switch):
  f = os.popen('uname %s' % switch)
  s = f.read().strip()
  f.close()
  return s

def host_arch():
  """Host architecture. One of arm, ia32 or x64."""
  arch = uname('-p')

  if arch == 'unknown':
    arch = uname('-m')

  return {
    'arm': 'arm',
    'x86': 'ia32',
    'i386': 'ia32',
    'x86_64': 'x64',
  }.get(arch, 'ia32')


def target_arch():
  return host_arch()


def configure_gems(o):
  o['variables']['host_arch'] = host_arch()
  o['variables']['target_arch'] = target_arch()


print "configure options:", options

output = {
  'variables': {},
  'include_dirs': [],
  'libraries': [],
  'defines': [],
  'cflags': [],
}

configure_gems(output)

# variables should be a root level element,
# move everything else to target_defaults
variables = output['variables']
del output['variables']
output = {
  'variables': variables,
  'target_defaults': output
}

fn = os.path.join(root_dir, 'build', 'options.gypi')
print "creating ", fn

f = open(fn, 'w+')
f.write("# Do not edit. Generated by the configure script.\n")
json.dump(output, f, indent=2, skipkeys=True)
f.write("\n")
f.close()

subprocess.call(['build/run_gyp'])
